package com.sinosun.autotestmachine.tools.proxy;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.sinosun.autotestmachine.tools.ValueInfo;
import com.sinosun.autotestmachine.tools.ValueType;
import com.sinosun.autotestmachine.tools.Collector.Cache;
import com.sinosun.autotestmachine.tools.parser.ParamKey;
import com.sinosun.autotestmachine.tools.utils.Utils;
import com.sinosun.mstplib.MstpClient;
import com.sinosun.mstplib.MstpException;
import com.sinosun.mstplib.vote.QuestionType;
import com.sinosun.mstplib.vote.Vote;
import com.sinosun.mstplib.vote.VoteInfo;
import com.sinosun.mstplib.vote.VoteOption;
import com.sinosun.mstplib.vote.VoteOptionInfo;
import com.sinosun.mstplib.vote.VoteOptionResult;
import com.sinosun.mstplib.vote.VoteQuestion;
import com.sinosun.mstplib.vote.VoteQuestionInfo;
import com.sinosun.mstplib.vote.VoteResult;
import com.sinosun.mstplib.vote.VoteSuggestionResult;
import com.sinosun.mstplib.vote.VoteType;
import com.sinosun.mstplib.vote.VoteAnswer;

import android.text.TextUtils;
import android.util.Log;

public class VoteModule {
	
	public static int createVote(MstpClient mstpClient, String paramJson, String cacheJson) {
		try {
			JSONObject jo = new JSONObject(paramJson);
			Vote vote = new Vote();
			String cacheIndex = null;
			if (jo.has(ParamKey.TITLE)) {
				vote.setTitle(jo.getString(ParamKey.TITLE));
			}
			if (jo.has(ParamKey.VOTE_DESC)) {
				vote.setDescription(jo.getString(ParamKey.VOTE_DESC));
			}
			if (jo.has(ParamKey.START_TIME)) {
				if (TextUtils.isEmpty(jo.getString(ParamKey.START_TIME))) {
					vote.setstartTime(0);
				} else {
					vote.setstartTime(Long.valueOf(jo.getString(ParamKey.START_TIME)));
				}
			}
			if (jo.has(ParamKey.END_TIME)) {
				if (TextUtils.isEmpty(jo.getString(ParamKey.END_TIME))) {
					vote.setEndTime(0);
				} else {
					vote.setEndTime(Long.valueOf(jo.getString(ParamKey.END_TIME)));
				}
			}
			if (jo.has(ParamKey.VOTE_TYPE)) {
				vote.setVoteType(VoteType.valueOf(jo.getInt(ParamKey.VOTE_TYPE)));
			}
			if (jo.has(ParamKey.QUESTIONS)) {
				JSONArray questionsJa = jo.getJSONArray(ParamKey.QUESTIONS);
				List<VoteQuestion> voteQuestions = new ArrayList<VoteQuestion>();
				for (int i = 0; i < questionsJa.length(); i++) {
					JSONObject quetstionJo = questionsJa.getJSONObject(i);
					VoteQuestion item = new VoteQuestion();
					if (quetstionJo.has(ParamKey.QUESTION_TITLE)) {
						item.setQuestionTittle(quetstionJo.getString(ParamKey.QUESTION_TITLE));
					}
					if (quetstionJo.has(ParamKey.QUESTION_TYPE)) {
						item.setQuestionType(QuestionType.valueOf(quetstionJo.getInt(ParamKey.QUESTION_TYPE)));
					}
					if (quetstionJo.has(ParamKey.OPTIONS)) {
						JSONArray optionsJa = quetstionJo.getJSONArray(ParamKey.OPTIONS);
						List<VoteOption> voteOptions = new ArrayList<VoteOption>();
						for (int j = 0; j < optionsJa.length(); j++) {
							JSONObject optionJo = optionsJa.getJSONObject(j);
							VoteOption ele = new VoteOption();
							if (optionJo.has(ParamKey.CONTENT)) {
								ele.setContent(optionJo.getString(ParamKey.CONTENT));
							}
							voteOptions.add(ele);
						}
						item.setOptions(voteOptions);
					}
					voteQuestions.add(item);
				}
				vote.setQuestions(voteQuestions);
			}
			
			if (cacheJson != null) {
				JSONObject cacheJo = new JSONObject(cacheJson);
				if (cacheJo.has(ParamKey.VOTE_INFO) && !cacheJo.isNull(ParamKey.VOTE_INFO)) {
					cacheIndex = cacheJo.getString(ParamKey.VOTE_INFO);
				} else {
					return ErrorCode.ERR_PARAM_ERROR;
				}
			}
			VoteInfo vi = mstpClient.getVoteManager().createVote(vote);
			for (VoteQuestionInfo item : vi.getQuestions()) {
				for (VoteOptionInfo ele : item.getOptions()) {
					Log.e("XXX", "content " + ele.getContent());
					Log.e("XXX", "content " + ele.getOptionId());
				}
			}
			if (cacheIndex != null) {
				Cache.allVoteInfo.put(cacheIndex, vi);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (MstpException e) {
			e.printStackTrace();
			return e.getErrorCode();
		}
		return ErrorCode.SUCCESS;
	}
	
	public static int submitVote(MstpClient mstpClient, String paramJson) {
		try {
			JSONObject jo = new JSONObject(paramJson);
			String voteId;
			List<VoteAnswer> voteAnwsers = new ArrayList<>();
			if (jo.has(ParamKey.VOTE_ID)) {
				voteId = getVoteId(jo);
			} else {
				return ErrorCode.ERR_PARAM_ERROR;
			}
			
			VoteInfo voteInfo = getVoteInfo(jo);
			if (jo.has(ParamKey.ANSWERS) && !jo.isNull(ParamKey.ANSWERS)) {
				JSONArray ja = jo.getJSONArray(ParamKey.ANSWERS);
				for (int i = 0; i < ja.length(); i++) {
					JSONObject eleJo = ja.getJSONObject(i);
					if (eleJo.has(ParamKey.OPTION_IDS)  || eleJo.has(ParamKey.SUGGESTION)) {
						VoteAnswer ele = new VoteAnswer();
						ele.setQuestionId(voteInfo.getQuestions().get(i).getQuestionId());
						if (eleJo.has(ParamKey.OPTION_IDS)) {
							ele.setQuestionId(voteInfo.getQuestions().get(i).getQuestionId());
							if (eleJo.isNull(ParamKey.OPTION_IDS)) {
								ele.setOptionIds(null);
							} else {
								JSONArray optionJa = eleJo.getJSONArray(ParamKey.OPTION_IDS);
								List<String> options = new ArrayList<String>();
								for (int k = 0; k < optionJa.length(); k++) {
									options.add(voteInfo.getQuestions().get(i).getOptions().get(k).getOptionId());
								}
								ele.setOptionIds(options);
								
							}
						}
						if (eleJo.has(ParamKey.SUGGESTION)) {
							if (eleJo.isNull(ParamKey.SUGGESTION)) {
								ele.setSuggestion(null);
							} else {
								ele.setSuggestion(eleJo.getString(ParamKey.SUGGESTION));
							}
						}
						voteAnwsers.add(ele);
					}
				}
			}
			Log.e("XXX", "submitVote voteId " + voteId);
			int ret = mstpClient.getVoteManager().submitVoteWithVoteId(voteId, voteAnwsers);
			if (ret != ErrorCode.SUCCESS) {
				return ret;
			}
			List<VoteResult> voteResults = mstpClient.getVoteManager().queryVoteResultWithVoteId(voteId);
			Log.e("XXX", "voteResults size=" + voteResults.size());
			int tag = 0;
			for(VoteAnswer ele : voteAnwsers) {			//提交的投票结果
				for (VoteResult item : voteResults) {	//返回的投票结果
					if (ele.getQuestionId().equals(item.getQuestionId())) {		//相同的问题ID的对比
						if (!(ele.getOptionIds() == null || ele.getOptionIds().size() == 0)) {		//提交的问题中存在选项
							List<String> oIds = new ArrayList<String>();
							for (VoteOptionResult or : item.getOptionResult()) {
								if (or.getMembers().contains(mstpClient.getMstpId())) {		//获取当前用户的所有选项
									oIds.add(or.getOptionId());
								}
							}
								
							if (oIds.containsAll(ele.getOptionIds())) {		//相同的问题指定用户存在包含的选项
								tag++;
								break;
							}
						} else {			//提交的问题不存在选项
							for (VoteSuggestionResult suggestion : item.getSuggestionResults()) {
								if (suggestion.getMstpId().equals(mstpClient.getMstpId()) && ele.getSuggestion().equals(suggestion.getAnswer())) {
									tag++;
									break;
								}
							}
						}
					}
				}
			}
			if (tag == voteAnwsers.size()) {
				return ErrorCode.SUCCESS;
			}
		} catch (JSONException e) {
			e.printStackTrace();
			return ErrorCode.ERR_PARAM_ERROR;
		} catch (MstpException e) {
			e.printStackTrace();
			return e.getErrorCode();
		}
		return ErrorCode.ERR_UNEXPECT_RESULT;
	}
	
	public static int queryVoteResult(MstpClient mstpClient, String paramJson) {
		try {
			JSONObject jo = new JSONObject(paramJson);
			String voteId;
			if (jo.has(ParamKey.VOTE_ID)) {
				voteId = getVoteId(jo);
			} else {
				return ErrorCode.ERR_PARAM_ERROR;
			}
			Log.e("XXX", "queryVoteResult voteId=" + voteId + ".");
			mstpClient.getVoteManager().queryVoteResultWithVoteId(voteId);
			return ErrorCode.SUCCESS;
		} catch (JSONException e) {
			e.printStackTrace();
			return ErrorCode.ERR_PARAM_ERROR;
		} catch (MstpException e) {
			e.printStackTrace();
			return e.getErrorCode();
		}
	}
	
	private static String getVoteId(JSONObject jo) throws JSONException {
		if (jo.isNull(ParamKey.VOTE_ID)) {
			return null;
		}
		
		VoteInfo voteInfo = getVoteInfo(jo);
		if (voteInfo == null) {
			return jo.getString(ParamKey.VOTE_ID);
		} else {
			return voteInfo.getVoteId();
		}
	}
	
	private static VoteInfo getVoteInfo(JSONObject jo) throws JSONException {
		if (jo.isNull(ParamKey.VOTE_ID)) {
			return null;
		}
		String index = jo.getString(ParamKey.VOTE_ID);
		ValueInfo vi = Utils.getRealVoteInfo(index);
		if (vi.getValueType() == ValueType.INDEX) {
			VoteInfo get = Cache.allVoteInfo.get(index);
			return get;
		}
		return null;
	}

}
